package com.abc.controller;

import com.abc.dao.ExampleMapper;
import com.abc.dao.base.ExampleBaseMapper;
import com.abc.entity.Example;
import com.abc.util.StringUtils;
import com.abc.vo.ExampleVo;
import com.abc.vo.Json;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(value = "/example", tags = "案例")
@RestController
@RequestMapping("/api/v1/example")
public class ExampleController {
    @Autowired
    ExampleMapper exampleMapper;
    @Autowired
    ExampleBaseMapper exampleBaseMapper;

    @PostMapping("findExampleListWithImage")
    @ApiOperation(value = "findExampleListWithImage", notes = "获取案例")
    public Json findExampleListWithImage() {
        List<ExampleVo> list = exampleMapper.findExampleListWithImage();
        return Json.succ("findExampleListWithImage", "list", list);
    }


    @PostMapping("getExampleById")
    @ApiOperation(value = "getExampleById", notes = "获取案例")
    public Json getExampleById(@RequestBody ExampleVo example) {
        ExampleVo res = exampleMapper.getExampleById(ExampleVo.Build().id(example.getId()).build());
        return Json.succ("getExampleById", res);
    }


    @PostMapping("saveExample")
    @ApiOperation(value = "saveExample", notes = "保存案例")
    public Json saveExample(@RequestBody Example example) {
        int subLength = example.getName().length() > 6 ? 6 : example.getName().length();
        example.setLowerCase(StringUtils.toPinyin(example.getName().substring(0, subLength)));
        if (example.getId() == null) {
            //新增
            exampleBaseMapper.insertExample(example);
        } else {
            exampleBaseMapper.updateExample(example);
        }
        return Json.succ("saveExample");
    }

    @PostMapping("removeExampleById")
    @ApiOperation(value = "removeExampleById", notes = "删除")
    public Json removeExampleById(@RequestBody ExampleVo example) {
        int count = exampleMapper.delExampleById(example);
        if (count > 0) {
            return Json.succ("removeExampleById");
        } else {
            return Json.fail("removeExampleById");
        }
    }

    @PostMapping("refreshExampleSort")
    @ApiOperation(value = "refreshExampleSort", notes = "刷新案例排序")
    public Json refreshExampleSort(@RequestBody List<Example> exampleList) {
        for (Example example : exampleList) {
            Example example1 = new Example();
            example1.setId(example.getId());
            example1.setOrder(example.getOrder());
            example1.setTop(example.getTop());
            exampleBaseMapper.updateExample(example1);
        }
        return Json.succ("refreshExampleSort");
    }
}
